<?php
/**
 *  Discuz! specified functions
 **/
if(!defined('CURSCRIPT')) {
	exit('Access Denied');
}

require_once DISCUZ_ROOT.'./include/misc.func.php';
require_once DISCUZ_ROOT.'./uc_client/client.php';

/**
 * Call the Discuz! register.php using HTTP Request and Forward the cookies
 * 
 * @param $username: a legal and available username
 * @param $password: a genrated password
 * @param $email: the email address
 * @param $formhash: for HTTP Request
 * @return true if register successfully. false if failed
 */
function DiscuzRegisterHTTP($username, $password, $email, $formhash) {
  /**
   * In this function, we will update the session stored in database manually.
   * This is a hack, not so elegant
   * */
  global $gfcconfig;
  global $db;
  global $tablepre;
  global $cookiepre;
  global $onlineip;
  global $regname;
  $registerurl = $gfcconfig['sitepath']."$regname?regsubmit=yes";
  $postdata = "formhash={$formhash}&handlekey=register&activationauth=&".
              "username={$username}&password={$password}&password2={$password}&".
              "email={$email}";
  $return = httpgets($registerurl, $postdata);
  if (!$return) {
    return false;
  }
  $content = $return['body'];
  $headers = $return['headers'];
  foreach ($headers as $header) {
    header($header, false);
    $head = explode(';', $header);
    $head = $head[0];
    $pos = stripos($head, "{$cookiepre}sid");
    if ($pos !== false) {
      $sid = substr($head, $pos + strlen("{$cookiepre}sid="));
      break;
    }
  }
  $session = $db->fetch_first("SELECT uid 
                               FROM {$tablepre}sessions
                               WHERE sid='$sid' AND uid>0");
  if ($session) {
    //update session
    $ips = explode('.', $onlineip);
    $db->query("UPDATE {$tablepre}sessions
                set ip1=$ips[0], ip2=$ips[1], ip3=$ips[2], ip4=$ips[3]
                WHERE sid='$sid'");
  } else {
    debuglog($content);
    return false;
  }
  return true;
}

/**
 * Call the Discuz! logging.php using HTTP Request and Forward the cookies
 * 
 * @param $username: A registered username
 * @param $password: The password of the $username
 * @return true if login sucefully. false if login failed
 */
function DiscuzLoginHTTP($username, $password) {
  global $gfcconfig;
  global $cookiepre;
  $loginurl = $gfcconfig['sitepath']."/logging.php?action=login&loginsubmit=yes";
  $postdata = "loginfield=username&username={$username}&password={$password}&".
              "questionid=0&answer=&cookietime=2592000";
  $return = httpgets($loginurl, $postdata);
  if (!$return) {
    return false;
  }
  $headers = $return['headers'];
  $content = $return['body'];
  foreach ($headers as $header) {
    header($header, FALSE);
    $head = explode(';', $header);
    $head = $head[0];
    $pos = stripos($head, "{$cookiepre}auth");
    if ($pos !== false) {
      $auth = substr($head, $pos + strlen("{$cookiepre}auth="));
    }
  }
  if (isset($auth)) {
    header("Content-Type: text/html;");
    return true;
  } else {
    return false;
  }
}

/**
 * Register the GFC user at Discuz!. This includes mapping the GFCid-username,
 * registering at Discuz!
 * 
 * @param $profile: profile got from GFC
 * @param $username: the username to be registered at Disucz!
 * @param $email:
 * @param $formhash: for HTTP Request
 * @return true if register is successfully. false otherwise.
 */
function GFCRegister($profile, $username, $email, $formhash, $regip) {
  global $db;
  global $tablepre;
  $gfcid = $profile['id'];
  $password = random(8);
  $db->query("INSERT INTO {$tablepre}gfcmapping (gfcid, dzusername, dzpassword)
              VALUES ('$gfcid', '$username', '$password')");
  //register
  $status = DiscuzRegisterHTTP($username, $password, $email, $formhash, $regip);
  if ($status) {
    return $status;
  } else {
    //delete mapping if register failed
    $db->query("DELETE FROM {$tablepre}gfcmapping WHERE gfcid='$gfcid'");
    return false;
  }
}

/**
 * Login to Discuz!. This includes get the username and password from DB and 
 * call Disucz! loggingh.php using HTTP Request
 * 
 * @param $gfcid: the gfcid of the user
 * @return true if login successfully. false if failed
 */
function GFCLogin($gfcid) {
  global $db;
  global $tablepre;
  global $discuz_userss;
  $entry = $db->fetch_first("SELECT gfcid, dzusername, dzpassword
                             FROM {$tablepre}gfcmapping
                             WHERE gfcid='$gfcid'");
  if (!$entry) {
    return false;
  }
  $username = $entry['dzusername'];
  $password = $entry['dzpassword'];
  $status = DiscuzLoginHTTP($username, $password);
  if ($status) {
    $discuz_userss = $username;
  }
  return $status;
}

/**
 * Check whether a GFCid is registered
 * 
 * @param $gfcid
 * @return true if it is registered, false otherwise.
 */
function IsGFCidRegistered($gfcid) {
  global $db;
  global $tablepre;
  $entry = $db->fetch_first("SELECT gfcid, dzusername
                             FROM {$tablepre}gfcmapping
                             WHERE gfcid='$gfcid'");
  if ($entry) {
    $username = $entry["dzusername"];
    $ucresult = uc_user_checkname($username);
    if ($ucresult == -3) {
      //username exists
      return true;
    } else {
      $db->query("DELETE FROM {$tablepre}gfcmapping WHERE gfcid='$gfcid'");
      return false;
    }
  } else {
    return false;
  }
}

/**
 * Check whether a username is available
 * 
 * @param $username: the username to be checked
 * @return true if the username is available. false otherwise
 */
function  IsUserNameAvailable($username) {
  $ucresult = uc_user_checkname($username);
  if ($ucresult < 0) {
    return false;
  } else {
    return true;
  }
}

/**
 * 
 * @param $profile
 * @param $uid
 * @param $level
 * @return void
 */
function SyncUserProfile($profile, $uid, $level) {
  global $db;
  global $tablepre;
  $gfcid = $profile['id'];
  $thumbnail = $profile['thumbnailUrl'];
  if (($level & 1) && $thumbnail) {
    $entry = $db->fetch_first("SELECT thumbnail_url
                               FROM {$tablepre}gfcmapping
                               WHERE gfcid='$gfcid'");
    if (!($entry && $entry['thumbnail_url'] == $thumbnail)) {
      //the $thumbnail need update
      $response = httpgets($thumbnail);
      $image = $response['body'];
      $uid = abs(intval($uid));
      $uid = sprintf("%09d", $uid);
      //create the directories
      $basedir = DISCUZ_ROOT.'./uc_server/data/avatar/';
      $dir1 = $basedir.substr($uid, 0, 3);
      $dir2 = $dir1.'/'.substr($uid, 3, 2);
      $dir3 = $dir2.'/'.substr($uid, 5, 2);
      !is_dir($dir1) && @mkdir($dir1, 0777);
      !is_dir($dir2) && @mkdir($dir2, 0777);
      !is_dir($dir3) && @mkdir($dir3, 0777);
      //file names
      $smallavatarfile = $dir3.'/'.substr($uid, -2)."_avatar_small.jpg";
      $middleavatarfile = $dir3.'/'.substr($uid, -2)."_avatar_middle.jpg";
      $bigavatarfile = $dir3.'/'.substr($uid, -2)."_avatar_big.jpg";
      //write the files
      $fp = @fopen($smallavatarfile, 'wb');
      @fwrite($fp, $image);
      @fclose($fp);
      $fp = @fopen($middleavatarfile, 'wb');
      @fwrite($fp, $image);
      @fclose($fp);
      $fp = @fopen($bigavatarfile, 'wb');
      @fwrite($fp, $image);
      @fclose($fp);
    }
  }
  //TODO: two db query ===> one
  $about_me = $profile['aboutMe'];
  if (($level & 2) && $about_me) {
    //TODO check security
    $query = "UPDATE {$tablepre}memberfields
              SET bio='$about_me'
              WHERE uid='$uid'";
    $db->query($query);
  }
  $urls = $profile['urls'];
  if (($level & 4) && $urls) {
    //TODO check security
    foreach ($urls as $url) {
      if ($url['type'] == 'externalProfile') {
        $site = $url['value'];
        $query = "UPDATE {$tablepre}memberfields
                  SET site='$site'
                  WHERE uid='$uid'";
        $db->query($query);
        break;
      }
    }
  }
  $gfcid = $profile['id'];
  $db->query("UPDATE {$tablepre}gfcmapping
              SET site='$site', bio='$about_me', thumbnail_url='$thumbnail'
              WHERE gfcid='$gfcid'");
}

/**
 * Check whether a user's GFC profile has been changed since last profile sync
 * 
 * @param $profile
 * @param $uid
 * @return 1 if thumbnail changed. 2 if bio changed. 4 if url changed.
 * 				 0 if nothing changed.
 */
function CheckProfile($profile) {
  global $db;
  global $tablepre;
  global $thum_url_before;
  global $thum_url_after;
  global $thum_bio_before;
  global $thum_bio_after;
  global $thum_site_before;
  global $thum_site_after;
  $ret = 0;
  $gfcid = $profile['id'];
  $entry = $db->fetch_first("SELECT thumbnail_url, bio, site
                             FROM {$tablepre}gfcmapping
                             WHERE gfcid='$gfcid'");
  if ($entry) {
    $thumbnail = $profile['thumbnailUrl'];
    $about_me = $profile['aboutMe'];
    $urls = $profile['urls'];
    $site = '';
    if ($urls) {
      foreach ($urls as $url) {
        if ($url['type'] == 'externalProfile') {
          $site = $url['value'];
          break;
        }
      }
    }
    if ($thumbnail && $thumbnail != $entry['thumbnail_url'] ) {
      $thum_url_before = $entry['thumbnail_url'];
      $thum_url_after = $thumbnail;
      $ret = $ret | 1;
    }
    if ($about_me && $about_me != $entry['bio'] ) {
      $thum_bio_before = $entry['bio'];
      $thum_bio_after = $about_me;
      $ret = $ret | 2;
    }
    if ($site && $site != $entry['site'] ) {
      $thum_site_before = $entry['site'];
      $thum_site_after = $site;
      $ret = $ret | 4;
    }
  }
  return $ret;
}
?>